import React from 'react'
import { info, success, TitleBar } from '../../ui-components'
import { u } from '../../actions/util'
import { connect } from 'react-redux'
import style from './style.basic'
import UserProfile from './UserProfile'
import util from '../../util'
import {TemplateMap,getFieldGroup}  from '../../constants/fieldsMap'

export default
@connect(({ user, app }) => ({ user, app }))
class extends React.Component {

	state = {}

	componentDidMount() {
		this.props.fetchUserProfile(u.userId)
	}

	componentWillUnmount() {
		this.props.resetUser()
	}

  handleSave(changed) {
    if (!util.isNull(changed)) {
      info('更新中...', true)
      this.props.updateUserProfile(u.userId, changed, () => {
        if (changed.avatarUrl) {
          this.props.fetchProfile(u.userId)
        }

        success('更新成功!')
        if (this.props.location.query.from === 'head') return
        this.props.router.push(`/user/${u.userId}`)
      })
    } else {
      info('无任何改动!')
      if (this.props.location.query.from === 'head') return
      this.props.router.push(`/user/${u.userId}`)
    }
  }

  filter(list) {
    return list.filter(v => v.referenceName !== 'essentialInfo')
  }
	
	render() {
		const { profile } = this.props.user 
		const { profileFieldVOs=[] } = profile
		return (
			<div>
				<TitleBar 
					label="个人信息设置"
				/>
        <div>
          <UserProfile
            fields={getFieldGroup(TemplateMap, profileFieldVOs) || [] }
            fetchAddresses={this.props.fetchAddresses}
            app={this.props.app}
            createDocument={this.props.createDocument}
            fileUpload={this.props.fileUpload}
            updateAvatar={this.props.updateAvatar}
            onSave={::this.handleSave}
            userId={u.userId}
            label="更新"
          />
        </div>
			</div>
		)
	}
}
